# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/10/18
# @File   : EJ50_Ent1yearJudCaseCnt.py
# @E-mail : zhaochen@bbdservice.com
'''eof
name:申请企业近1年司法案件总数(裁判文书）
code:EJ50_Ent1yearJudCaseCnt
tableName:
columnName:
groups:企业通用模块
dependencies:EG_CASE_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import pandas as pd
import json
from datetime import datetime
# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def FormatData(tableName):
    try:
        eg = EG_CASE_DSJ.get("data").get(tableName)
        if eg in null_type_list:
            return None
        if isinstance(eg, list):
            return eg
        else:
            return None
    except:
        return None


# 统一转成datetime对象，只能转年月日的字符串
def date_format(str):
    import re
    r = re.compile(r'\D+')
    try:
        time = str[0:10]
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-12, 0]]
        return aaa
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def EG_Ent2YearsCrimCaseCnt():
    try:
        info = FormatData("R227")
        if info is None:
            return u'缺失值'
        else:
            CASENOS = []
            for i in info:
                PTYPE = i.get('PTYPE', '')
                CASEDATE = i.get('CASEDATE', '')
                CASENO = i.get('CASENO', '')
                if PTYPE not in null_type_list and date_format(CASEDATE) and CASENO not in null_type_list:
                    if PTYPE in ['16'] and int(get_date_list()[0]) <= int(date_format(CASEDATE)) <= int(get_date_list()[1]):
                        CASENOS.append(CASENO)
                    else:
                        CASENOS.append(0)
                else:
                    CASENOS.append('None')
            if len(list(set(CASENOS))) == 1 and list(set(CASENOS))[0] == 'None':
                return u'缺失值'
            elif len(list(set([i for i in CASENOS if i != 'None']))) == 1 and list(set([i for i in CASENOS if i != 'None']))[0] == 0:
                return 0
            else:
                CASENOS = [i for i in CASENOS if i != 'None' and i != 0]
                return len(list(set(CASENOS)))

    except:
        return u'缺失值'

if __name__ == "__main__":
    import json
    with open(r'E:\zxc\samples\EG_CASE_DSJ.json') as ff:
        EG_CASE_DSJ = json.loads(ff.read())['EG_CASE_DSJ']
    res = EG_Ent2YearsCrimCaseCnt()
    print(res)

result = EG_Ent2YearsCrimCaseCnt()